require('dotenv').config();
const fs = require('fs').promises;
const path = require('path');

const backupService = require('./services/backupService');
const emailService = require('./services/emailService');
const schedulerService = require('./services/schedulerService');
const logger = require('./utils/logger');

class BackupApp {
    constructor() {
        this.isInitialized = false;
    }

    async ensureDirectories() {
        const directories = [
            './logs',
            './backups',
            process.env.BACKUP_DIR || './backups'
        ];

        for (const dir of directories) {
            try {
                await fs.access(dir);
            } catch (error) {
                logger.info(`创建目录: ${dir}`);
                await fs.mkdir(dir, { recursive: true });
            }
        }
    }

    async validateConfiguration() {
        const requiredEnvVars = [
            'DB_HOST',
            'DB_USER', 
            'DB_PASSWORD',
            'DB_NAME',
            'EMAIL_USER',
            'EMAIL_PASS'
        ];

        const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
        
        if (missingVars.length > 0) {
            throw new Error(`缺少必需的环境变量: ${missingVars.join(', ')}`);
        }

        logger.info('配置验证通过');
        return true;
    }

    async testConnections() {
        logger.info('测试服务连接...');
        
        try {
            // 测试邮件服务
            await emailService.testConnection();
            logger.info('✅ 邮件服务连接正常');
        } catch (error) {
            logger.error(`❌ 邮件服务连接失败: ${error.message}`);
            throw error;
        }

        logger.info('所有服务连接测试完成');
    }

    async initialize() {
        if (this.isInitialized) {
            logger.warn('应用已初始化，跳过重复初始化');
            return;
        }

        try {
            logger.info('🚀 启动数据库备份服务...');
            
            // 确保必要目录存在
            await this.ensureDirectories();
            
            // 验证配置
            await this.validateConfiguration();
            
            // 测试连接
            await this.testConnections();
            
            // 启动定时任务
            const schedulerResult = schedulerService.startScheduler();
            logger.info(`✅ 定时备份任务已启动: ${schedulerResult.schedule}`);
            logger.info(`📅 调度描述: ${schedulerService.getScheduleDescription()}`);
            
            this.isInitialized = true;
            logger.info('🎉 数据库备份服务初始化完成');
            
            // 输出配置信息
            this.logConfigurationInfo();
            
        } catch (error) {
            logger.error(`❌ 服务初始化失败: ${error.message}`);
            process.exit(1);
        }
    }

    logConfigurationInfo() {
        logger.info('📋 当前配置信息:');
        logger.info(`   数据库: ${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`);
        logger.info(`   邮件服务: ${process.env.EMAIL_HOST}:${process.env.EMAIL_PORT}`);
        logger.info(`   发件人: ${process.env.EMAIL_USER}`);
        logger.info(`   收件人数量: ${process.env.RECIPIENTS ? process.env.RECIPIENTS.split(',').length : 0}`);
        logger.info(`   备份目录: ${process.env.BACKUP_DIR || './backups'}`);
        logger.info(`   备份保留天数: ${process.env.BACKUP_RETENTION_DAYS || 7} 天`);
        logger.info(`   调度表达式: ${process.env.BACKUP_SCHEDULE || '0 2 * * *'}`);
    }

    async shutdown() {
        logger.info('🛑 正在关闭数据库备份服务...');
        
        try {
            // 停止定时任务
            schedulerService.stopScheduler();
            logger.info('✅ 定时任务已停止');
            
            logger.info('👋 数据库备份服务已安全关闭');
            process.exit(0);
        } catch (error) {
            logger.error(`❌ 关闭服务时出错: ${error.message}`);
            process.exit(1);
        }
    }

    // 手动执行备份（用于测试）
    async executeBackupNow() {
        try {
            logger.info('🔧 手动执行备份任务...');
            const result = await schedulerService.executeBackupNow();
            logger.info('✅ 手动备份完成');
            return result;
        } catch (error) {
            logger.error(`❌ 手动备份失败: ${error.message}`);
            throw error;
        }
    }

    // 获取服务状态
    getStatus() {
        return {
            initialized: this.isInitialized,
            scheduler: schedulerService.getStatus(),
            configuration: {
                database: `${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`,
                emailHost: process.env.EMAIL_HOST,
                backupDir: process.env.BACKUP_DIR || './backups',
                retentionDays: process.env.BACKUP_RETENTION_DAYS || 7,
                schedule: process.env.BACKUP_SCHEDULE || '0 2 * * *'
            },
            timestamp: new Date().toISOString()
        };
    }
}

// 创建应用实例
const app = new BackupApp();

// 处理进程信号
process.on('SIGINT', async () => {
    logger.info('接收到 SIGINT 信号');
    await app.shutdown();
});

process.on('SIGTERM', async () => {
    logger.info('接收到 SIGTERM 信号');
    await app.shutdown();
});

process.on('uncaughtException', (error) => {
    logger.error(`未捕获的异常: ${error.message}`);
    logger.error(error.stack);
    process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
    logger.error(`未处理的 Promise 拒绝: ${reason}`);
    process.exit(1);
});

// 启动应用
async function main() {
    try {
        await app.initialize();
        
        // 检查是否有命令行参数
        const args = process.argv.slice(2);
        
        if (args.includes('--test-backup')) {
            logger.info('🧪 执行测试备份...');
            await app.executeBackupNow();
            process.exit(0);
        }
        
        if (args.includes('--status')) {
            console.log(JSON.stringify(app.getStatus(), null, 2));
            process.exit(0);
        }
        
        // 保持进程运行
        logger.info('✨ 服务正在运行中，按 Ctrl+C 退出');
        
    } catch (error) {
        logger.error(`启动失败: ${error.message}`);
        process.exit(1);
    }
}

// 如果是直接运行此文件，则启动应用
if (require.main === module) {
    main();
}

module.exports = app; 